<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="detail-order-info">
    <div class="mb26">
      <Title title="问题信息" font-size="16px" style="margin-bottom: 6px;"/>
      <el-row :class="{'dividing':!showMobilePage}" class="detail-row">
        <el-form :class="{'mobile-el-form': showMobilePage}" label-position="right" label-width="110px">
          <el-col :span="8">
            <el-form-item label="问题编号：">
              <span>{{ detailData.sn || '--' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="问题类型：">
              <span :class="`question-type type${detailData.type}`">{{ formatQuestionType(detailData.type) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="回答次数：">
              <span>{{ detailData.number || '--' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号属性：">
              <span>{{ detailData.attribute ? '是' : '否' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人：">
              <CheckUserInfo :user-id="detailData.creatorId" :label="detailData.creator" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新人：">
              <CheckUserInfo :user-id="detailData.updaterId" :label="detailData.updater" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="问题名称：">
              <div v-if="[2,3].includes(detailData.type)" class="no-margin">
                <ToolTip :content="detailData.content" />
                <ToolTip v-for="(item,index) in detailData.selectList" :key="index" :content="`选项${index+1}：${item.label}`" />
              </div>
              <ToolTip v-else :content="detailData.content" />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>
    <div>
      <Title title="博主反馈记录" font-size="16px" style="margin-bottom: 16px;"/>
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          @selectChange="handelFilterInputChange"
          @deleteTagBefore="deleteTagBefore"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </div>
      <div class="table-list">
        <div v-loading="listLoading">
          <u-table
            v-if="list.items.length"
            ref="questionTableRef"
            :data="list.items"
            :border="true"
            :row-height="rowHeight(54)"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @sort-change="sortMethod">
            <u-table-column fixed="left" align="left" label="询单编号" min-width="150">
              <template slot-scope="scope">
                <div v-if="scope.row.sn" style="cursor:pointer;color:#406EFF;" @click="toFlyNoticeDetail(scope.row)">
                  <ToolTip :content="handleSnNumber(scope.row.sn)" />
                </div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="询单下单平台" min-width="150">
              <template slot-scope="scope">
                <template v-for="platform in (scope.row.queryOrderPlatform || [])">
                  <div :key="platform.id" class="flex-center" style="color: #999">
                    <platformIcon :data="platform.name" />
                    <ToolTip :content="platform.name" style="color: #333" />
                  </div>
                </template>
              </template>
            </u-table-column>
            <u-table-column align="left" label="询单合作形式" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.cooperationForm" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.accountName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号下单平台" min-width="150">
              <template slot-scope="scope">
                <div class="flex-center" style="color: #999">
                  <platformIcon :data="scope.row.platformName" />
                  <ToolTip :content="scope.row.platformName" style="color: #333" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="姓名" min-width="100">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.userName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="反馈内容" min-width="150">
              <template slot-scope="scope">
                <FileShowList v-if="showFile(scope.row)" :file-list="(scope.row.attachment || [])" style="max-width:100%;"/>
                <ToolTip v-else :content="scope.row.feedback" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="响应状态" min-width="100">
              <template slot-scope="scope">
                <div class="status">
                  <div :class="`color-${scope.row.responseStatus}`" class="dot"/>
                  <div v-if="scope.row.responseStatus===0" class="text">待响应</div>
                  <div v-else>{{ scope.row.responseStatus | responseStatus }}</div>
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="品牌名称" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.brandName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="产品名称" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.productName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="标签" min-width="200">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.tagName && scope.row.tagName.length" :open-delay="800" placement="top" effect="dark">
                  <div slot="content" style="max-width:300px">{{ handleStr(scope.row.tagName) }}</div>
                  <div class="flex-center">
                    <span v-for="(tag,index) in handleTags(scope.row.tagName)" :key="index" class="tag">
                      {{ tag.name }}
                    </span>
                    <div v-if="scope.row.tagName.length > 3">...</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="发布时间" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.publishTime, 'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="响应时间" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.responseTime, 'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row type="flex" justify="end">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[10, 20, 50]"
            :layout="showMobilePage?pageLayout:'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination>
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @selectChange="handelFilterInputChange"
              @deleteTagBefore="deleteTagBefore"
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <el-button type="primary" size="small" @click="handleEdit()">编辑</el-button>
            <el-button class="back-btn cancel-btn-style" size="small" @click="toBack()">返回</el-button>
          </template>
          <template v-else>
            <div class="bottom-flex">
              <el-button type="primary" size="small" @click="handleEdit()">编辑</el-button>
              <el-button class="back-btn cancel-btn-style" size="small" @click="toBack()">返回</el-button>
            </div>
          </template>
        </fixed-pagination>
      </div>
    </div>
    <addDialog ref="addQuestionRef" @updateData="getDetailData"/>
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import Title from '@/components/Title';
import addDialog from './components/addDialog.vue';
import FileShowList from '@/components/CreateOrder/fileShowList';
import { getQuestionDetail, getFeedbackList } from '@/api/question';
import { platformList, orderFormList } from '@/api/select';
import { getTagAll } from '@/api/config';
import { paramsAryToStr, paramsRangeFormat } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { generateUUID } from '@/utils/tools';
import { formatQuestionType, responseStatus } from '@/filters/status';
import { format } from '@/filters/date';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { mapState } from 'vuex';

export default {
  components: { Title, EmptyPlaceholder, platformIcon, addDialog, FileShowList },
  filters: { responseStatus },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      TAG_MODULES,
      id: '',
      detailData: {},
      list: {
        items: []
      },
      paramsObj: {},
      page: 1,
      perPage: 10,
      listLoading: false,
      orderPlatformOption: [],
      orderFormOption: [],
      tagTreeList: [],
      rangeKeyArr: [
        { attr: 'publishTime', start: 'publishTimeStart', end: 'publishTimeEnd', type: 'time', addTime: true },
        { attr: 'responseTime', start: 'responseTimeStart', end: 'responseTimeEnd', type: 'time', addTime: true }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      const arr = [
        { keyword: 'userName', name: '姓名', labelWidth: '100px', type: 'input' },
        { keyword: 'accountName', name: '账号', labelWidth: '100px', type: 'input' },
        { keyword: 'feedback', name: '反馈内容', labelWidth: '100px', type: 'input' },
        { keyword: 'sn', name: '询单编号', labelWidth: '100px', type: 'input' },
        { keyword: 'brandName', name: '品牌名称', labelWidth: '100px', type: 'input' },
        { keyword: 'productName', name: '产品名称', labelWidth: '100px', type: 'input' },
        { keyword: 'platformId', name: '询单下单平台', labelWidth: '150px', type: 'mulSelect', className: 'filter-tool-width140', options: this.orderPlatformOption },
        { keyword: 'cooperationFormId', name: '询单合作形式', type: 'mulSelect', className: 'filter-tool-width140', emptyText: this.cooperationEmptyText, options: this.orderFormOption },
        { keyword: 'responseStatus', name: '响应状态', type: 'select', options: [
          { value: 0, label: '待响应' },
          { value: 1, label: '感兴趣' },
          { value: 2, label: '暂不考虑' }
        ] },
        { keyword: 'tagName', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        { keyword: 'publishTime', name: '发布时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'responseTime', name: '响应时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    cooperationEmptyText() {
      const { platformId } = this.paramsObj;
      const isEmptyPlatform = (Array.isArray(platformId) && !platformId.length) || !platformId;
      return isEmptyPlatform ? '请先选择询单下单平台' : '暂无可选项';
    }
  },
  watch: {
    'paramsObj.platformId'(list) {
      if (!list || !list.length) {
        this.orderFormOption = [];
      }
    }
  },
  created() {
    this.id = this.$route.params.id;
    this.getDetailData();
    this.fetchData();
    this.platformList();
    this.queryTagTreeList();
    this.getOrderForm();
  },
  methods: {
    hasRouteAuth,
    formatQuestionType,
    format,
    // 下单平台
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 下单形式
    async getOrderForm() {
      const params = { platformId: this.paramsObj.platformId };
      paramsAryToStr(['platformId'], params);
      if (!params.platformId) {
        return;
      }
      try {
        const result = await orderFormList(params.platformId);
        if (result.data && result.data.length) {
          result.data.forEach(i => {
            i.label = i.value;
            i.value = i.id;
          });
        }
        this.orderFormOption = result.data;
        if (this.paramsObj.cooperationFormId) {
          const formId = this.orderFormOption.find(i => i.value === this.paramsObj.cooperationFormId);
          if (!formId) this.$set(this.paramsObj, 'cooperationFormId', '');
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 标签
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 详情数据
    async getDetailData() {
      const res = await getQuestionDetail(this.id);
      if (res.code === 200) {
        this.detailData = res.data;
      }
    },
    handelFilterInputChange({ value, item }) {
      if (item.keyword === 'platformId') {
        this.$set(this.paramsObj, 'cooperationFormId', '');
        this.getOrderForm();
      }
    },
    deleteTagBefore(key) {
      if (key === 'platformId') {
        this.$set(this.paramsObj, 'cooperationFormId', '');
      }
    },
    handleTags(tag = []) {
      if (!tag || tag.length === 0) {
        return [];
      }
      return tag.slice(0, 3);
    },
    handleStr(tag = []) {
      if (!tag || tag.length === 0) {
        return '';
      }
      return tag.map(el => el.name).join(',');
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData();
    },
    formatParams() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, paramsObj);
      paramsAryToStr(['tagName', 'platformId', 'cooperationFormId'], paramsObj);
      return paramsObj;
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      params.page = this.page;
      params.perPage = this.perPage;
      params.questionId = this.id;
      getFeedbackList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        this.list.isInit = false;
        console.log(err);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toFlyNoticeDetail(row) {
      const url = this.$router.resolve({
        name: 'flyNoticeDetail',
        query: { id: row.queryOrderId }
      });
      window.open(url.href, '_blank');
    },
    toBack() {
      this.$router.push({ name: 'question' });
    },
    handleEdit() {
      const data = {
        id: this.id,
        attribute: this.detailData.attribute,
        _uuid: generateUUID(),
        remarks: [{
          type: this.detailData.type,
          content: this.detailData.content,
          selectList: JSON.parse(JSON.stringify(this.detailData.selectList))
        }]
      };
      if ([2, 3].includes(data.remarks[0].type)) {
        data.remarks[0].selectList.forEach(item => {
          item._uuid = generateUUID();
        });
      }
      this.$refs.addQuestionRef.initData(0, data);
    },
    showFile(row) {
      return this.detailData.type === 5 && row.attachment;
    }
  }
};
</script>

<style scoped lang="scss">
@import "@/views/question/question.scss";
$bgc: #FD8546 0, #31CC9C 1, #999 2;
.detail-order-info {
  margin: 16px;
  min-height: calc(100vh - 80px);
  padding: 20px;
  background: #fff;
  padding-bottom: 55px;
  &.mobile-detail-wrap {
    padding: 12px 12px 55px 12px;
  }
  &::v-deep {
    .el-form-item {
      margin-bottom: 0;
    }
    .el-form-item .el-form-item__label {
      color: #999;
    }
    .el-form-item .el-form-item__content {
      color: #333;
    }
  }
  .mb26 {
    margin-bottom: 26px;
  }
}
.status{
  display: flex;
  align-items: center;
  position: relative;
  .text{
    white-space: nowrap;
  }
  .dot {
    position: absolute;
    left: -8px;
    display: inline-block;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    @each $c, $i in $bgc {
      &.color-#{$i} {
        background: $c;
      }
    }
  }
}
.dividing{
  &::v-deep {
    .el-col {
      .el-form-item__content {
        border-right: 1px solid #EBEEFD;
      }
      &:nth-child(3n) {
        .el-form-item__content {
          border-right: none;
        }
      }
    }
  }
}
.filter {
  margin-bottom: 16px;
}
.tag {
  display: inline-block;
  max-width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color:#406EFF;
  font-size: 12px;
  padding: 0px 8px;
  background: #eff4ff;
  border-radius: 10px;
  margin-right: 4px;
}
.no-margin {
  p {
    margin: 0;
  }
}
.bottom-flex {
  width: 100%;
  display: flex;
  justify-content: center;
  .cancel-btn-style {
    padding: 0;
    width: 80px;
    height: 30px;
    font-size: 14px;
    box-sizing: border-box;
  }
}
</style>
